import { ref } from "vue";
import { api } from "@/api";

interface PageParams {
  keywords?: string;
  category?: string;
  page?: number;
  pageSize?: number;
}

export function useProducts() {
  const products = ref<Array<any>>([]);
  const total = ref(0);

  async function getProductsByCat(id: number) {
    const res = (
      await api.get(`/cat_products`, {
        params: {
          cat: id,
        },
      })
    ).data;
    products.value = res?.data;
    return res?.msg;
  }

  async function getAllProducts(params: PageParams) {
    const res = (
      await api.get(`/products`, {
        params: {
          ...params,
        },
      })
    ).data;
    products.value = res?.data?.list;
    total.value = res?.data?.total;
    return res?.msg;
  }

  return {
    total,
    products,
    getProductsByCat,
    getAllProducts,
  };
}

export function useProduct() {
  const product = ref<any>({});

  async function getProductByID(id: string) {
    const res = (await api.get(`/products/${id}`)).data;
    product.value = res?.data;
    return res?.msg;
  }

  return {
    product,
    getProductByID,
  };
}
